package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.product.entity.BaseAttrInfo;
import com.atguigu.gmall.product.entity.BaseAttrValue;
import com.atguigu.gmall.product.mapper.BaseAttrInfoMapper;
import com.atguigu.gmall.product.service.BaseAttrInfoService;
import com.atguigu.gmall.product.service.BaseAttrValueService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 *
 */
@Service
public class BaseAttrInfoServiceImpl extends ServiceImpl<BaseAttrInfoMapper, BaseAttrInfo> implements BaseAttrInfoService {

    @Autowired
    BaseAttrValueService baseAttrValueService;

    @Override
    public List<BaseAttrInfo> getAttrAndValue(Long category1Id, Long category2Id, Long category3Id) {
        return baseMapper.getAttrAndValue(category1Id,category2Id,category3Id);
    }

    @Override
    public void saveAttrInfo(BaseAttrInfo baseAttrInfo) {
        boolean save = save(baseAttrInfo);
        Long id = baseAttrInfo.getId();

        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
        for (BaseAttrValue baseAttrValue : attrValueList) {
            baseAttrValue.setAttrId(id);
        }

        baseAttrValueService.saveBatch(attrValueList);
    }

    @Override
    public void updateAttrInfo(BaseAttrInfo baseAttrInfo) {
        updateById(baseAttrInfo);

        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();

        List<Long> ids = new ArrayList<>();
        for (BaseAttrValue baseAttrValue : attrValueList) {
            if (baseAttrValue.getId() != null){
                ids.add(baseAttrValue.getId());
            }
        }
        if (ids.size() > 0) {
            baseAttrValueService.lambdaUpdate()
                    .eq(BaseAttrValue::getAttrId, baseAttrInfo.getId())
                    .notIn(BaseAttrValue::getId, ids)
                    .remove();
        }else {
            baseAttrValueService.lambdaUpdate()
                    .eq(BaseAttrValue::getAttrId, baseAttrInfo.getId())
                    .remove();
        }

        for (BaseAttrValue attrValue : attrValueList) {
            if (attrValue.getId() == null) {
                attrValue.setAttrId(baseAttrInfo.getId());
                baseAttrValueService.save(attrValue);
            }else {
                baseAttrValueService.updateById(attrValue);
            }
        }
    }
}




